package com.smalldoor.thread.sync;

//锁的对象需要是在增删改的量，此处应该锁住账户而不是银行
public class UnSafeBack {

    public static void main(String[] args) {

        Account account = new Account(1000000,"启动资金");

        Drawing firstPeople = new Drawing(account,500000,"第一个取钱的人");
        Drawing secondPeople = new Drawing(account,1000000,"第二个取钱的人");

        firstPeople.start();
        secondPeople.start();
    }
}

class Account{

    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行 模拟取款

class Drawing extends Thread{
    Account account;//账户
    
    int drawingMoney;//去了多少钱
    
    int newMoney;//还有多少钱
    
    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        synchronized (account) {
            if (account.money -drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "余额不足");
                return;
            }

            //sleep可以放大问题
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //余额 = 原来的余额 - 取出的钱
            account.money = account.money - drawingMoney;
            //现在手里的钱
            newMoney = newMoney + drawingMoney;

            System.out.println(Thread.currentThread().getName() + "余额为：" + account.money);
            System.out.println(this.getName() + "手里的钱为：" + newMoney);
        }
    }
    
}
